package com.safety51.bootstrap.demo.dev;

import com.safety51.bootstrap.commons.constants.AuthorizationConstants;
import com.safety51.bootstrap.commons.context.UserInfoContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by liuyuancheng on 2021/9/26  <br/>
 *
 * @author liuyuancheng
 */
@Configuration
@WebFilter(urlPatterns = "/shengxingapi")
@Slf4j
public class DevUserInfoWebFilter extends OncePerRequestFilter {

    @Value("${spring.profiles.active:dev}")
    private String activeProfile;

    /**
     * Same contract as for {@code doFilter}, but guaranteed to be
     * just invoked once per request within a single request thread.
     * See {@link #shouldNotFilterAsyncDispatch()} for details.
     * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
     * default ServletRequest and ServletResponse ones.
     *
     * @param request
     * @param response
     * @param filterChain
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (activeProfile.equals("dev")) {
            // 重置线程本地变量
            UserInfoContext.reset();
            log.debug("processing web filter for authorization, and the accessToken is {}.", request.getHeader(AuthorizationConstants.AUTHORIZATION_CODE));
            UserInfoContext.UserInfo userInfo = UserInfoContext.UserInfo.builder()
                    .avatar("")
                    .enterpriseId("nanjinggongyizhuangb")
                    .userId("admin_njgyzb")
                    .enterpriseName("南京工艺装备制造有限公司")
                    .realName(request.getHeader("real_name"))
                    .accessToken(request.getHeader(AuthorizationConstants.AUTHORIZATION_CODE))
                    .build();
            UserInfoContext.setUserInfo(userInfo);
            filterChain.doFilter(request, response);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
